package com.itheima.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itheima.EmployeeService01;
import com.itheima.bean.Employee;
import com.itheima.bean.Params;
import com.itheima.bean.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService01 es;



    @GetMapping("/employee/login2/{data}")
    public R<String> login2(@PathVariable String data, HttpSession session) {

        //这里收到的data 仅仅是前端页面传递过来的一个json字符串，需要手动转化成JavaBean对象。
        System.out.println("data = " + data);

        return null;
    }
   //更新
    @PutMapping("/employee")
    public R updata(@RequestBody Employee employee,HttpSession session){
        employee.setUpdateTime(LocalDateTime.now());
        Employee employee1 = (Employee)session.getAttribute("employee");
        Long employee1Id = employee1.getId();
        employee.setUpdateUser(employee1Id);
        int row = es.updata(employee);
        if (row>0){
            return R.success("修改成功！");
        }else {
            return R.error("修改失败！");
        }
    }
    @GetMapping("/employee/{params}")
    public R<IPage> selectPage(@PathVariable String params){
        Params params1 = JSON.parseObject(params, Params.class);
        IPage<Employee> page = es.selectPage(params1);
        return R.success(page);
    }

    @PostMapping("/employee")
    public R<String> add(@RequestBody Employee employee,HttpSession session){
      Employee employee1 = (Employee)session.getAttribute("employee");
        Long id = employee1.getId();
        employee.setCreateUser(id);
       employee.setUpdateUser(id);
        int row = es.add(employee);
        if (row>0){
            return R.success("添加成功！");
        }else {
            return R.error("添加失败！");
        }
    }

    /**
     * 登录功能
     *
     * @param employee
     * @return
     */
    @PostMapping("/employee/login")
public R<String> login(@RequestBody Employee employee,HttpSession session){
        Employee employee1 = es.login(employee);
        R<String> r=null;
        if (employee1!=null){
            session.setAttribute("employee",employee1);
           r=  R.success("登陆成功！");
        }else {
          r=  R.error("登陆失败！");
        }
        return r;
    }


    /**
     * 退出登录
     * @param session
     * @return
     */
   @GetMapping("/employee/logout")
    public R<String> logout(HttpSession session){
       R<String> r=null;
       try {
           session.invalidate();
           r=R.success("退出成功！");
       } catch (Exception e) {
           e.printStackTrace();
           r=R.error("退出失败！");
       }
       return r;
   }
}
